package com.scommunity.admin.controller;

import com.github.pagehelper.PageInfo;
import com.scommunity.admin.vo.OwnerQO;
import com.scommunity.common.ResponseResult;
import com.scommunity.domain.*;
import com.scommunity.service.IHouseService;
import com.scommunity.service.IOwnerService;
import com.scommunity.service.IUserService;
import com.scommunity.utils.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin/owner")
public class OwnerController {
    @Autowired
    IOwnerService ownerService;
    @Autowired
    IHouseService houseService;
    @Autowired
    IUserService userService;
    @Autowired
    SnowflakeIdWorker snowflakeIdWorker;

    @GetMapping({"/list/{pageNum}"})
    public Object list(OwnerQO ownerQO, @PathVariable(required = false) Integer pageNum) {
        if (pageNum == null) {
            pageNum = 1;
        }
        PageInfo<Owner> pageInfo = ownerService.findPageInfoByCondition(ownerQO, pageNum, 4);
        return ResponseResult.success(pageInfo);
    }

    @GetMapping("/getAll")
    public Object getAll() {
        List<Owner> owners = ownerService.getAll();
        return ResponseResult.success(owners);
    }

    @PostMapping("/add")
    public Object add(@RequestBody Owner owner) {
        owner.setUserId(snowflakeIdWorker.nextId());
        ownerService.add(owner);
        userService.addUser(new User(owner.getUserId(), owner.getOwnerPhone(), "123456", "1"));
        return ResponseResult.success();
    }

    @PostMapping("/update")
    public Object update(@RequestBody Owner owner) {
        ownerService.update(owner);
        return ResponseResult.success();
    }

    @GetMapping("/del")
    public Object del(String id) {
        if (ownerService.getStatuseById(id) == 0) {
            userService.updateUserStatusById(id, "0");
            ownerService.del(id);
            return ResponseResult.success();
        } else {
            return ResponseResult.error(201, "业主已入住，不能删除");
        }
    }

    @GetMapping("/addOwnerHouse")
    public Object addOwnerHouse(String ownerId, String houseId) {
        ownerService.addOwnerHouse(ownerId, houseId);
        houseService.updateHouseStatusById(houseId, "1");
        if (houseService.getOwnerHouses(ownerId).size() != 0) {
            ownerService.updateHouseStatusById(ownerId, "1");
        }
        return ResponseResult.success();
    }

    @GetMapping("/delOwnerHouse")
    public Object delOwnerHouse(String ownerId, String houseId) {
        ownerService.delOwnerHouse(ownerId, houseId);
        houseService.updateHouseStatusById(houseId, "0");
        if (houseService.getOwnerHouses(ownerId).size() == 0) {
            ownerService.updateHouseStatusById(ownerId, "0");
        }
        return ResponseResult.success();
    }
}
